package com.yy.wga.admin.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yy.wga.mp.common.interceptor.RequestUserHolder;
import com.yy.wga.mp.common.utils.mapping.BeansUtils;
import com.yy.wga.admin.service.pojo.AdminMenuDO;
import com.yy.wga.mp.module.admin.mapper.AdminMenuMapper;
import com.yy.wga.mp.module.admin.response.AdminMenuInfoResponse;
import com.yy.wga.mp.module.admin.service.AdminMenuService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 菜单信息(AdminMenu)表服务实现类
 *
 * @author guochao
 * @since 2024-11-06 22:56:23
 */
@Service
public class AdminMenuServiceImpl extends ServiceImpl<AdminMenuMapper, AdminMenuDO> implements AdminMenuService {
    @Override
    public List<AdminMenuInfoResponse> listMenus() {
        List<AdminMenuDO> menuList = baseMapper.selectList(new LambdaQueryWrapper<AdminMenuDO>()
                .eq(AdminMenuDO::getAppKey, RequestUserHolder.getBaseRequest().getAppKey()));
        menuList.sort(Comparator.comparing(AdminMenuDO::getSort).reversed());
        List<AdminMenuInfoResponse> responseList = BeansUtils.mapList(menuList, AdminMenuInfoResponse.class);
        responseList = this.getMenuTree(responseList, 0L);
        return responseList;
    }

    /**
     * 生成tree结构菜单
     * @param responseList 菜单列表
     * @param parentMenuId 上级id，第一级为0
     * @return tree结构菜单
     */
    public List<AdminMenuInfoResponse> getMenuTree(List<AdminMenuInfoResponse> responseList, Long parentMenuId) {
        if (CollectionUtils.isEmpty(responseList)) {
            return Collections.emptyList();
        }
        List<AdminMenuInfoResponse> menus = new ArrayList<>();
        for (AdminMenuInfoResponse response : responseList) {
            if (response.getParentMenuId().equals(parentMenuId)) {
                menus.add(response);
                List<AdminMenuInfoResponse> childMenus = this.getMenuTree(responseList, response.getId());
                response.setChildMenus(childMenus);
            }
        }
        return menus;
    }
}
